#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class Solution
{
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    bool temp[101][101] = { false };

public:
    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance)
    {
        int ret = 0;
        int x = entrance.front();
        int y = entrance.back();

        return bfs(maze, x, y);
    }

    int bfs(vector<vector<char>>& maze, int i, int j)
    {
        queue<pair<int, int>>q;
        q.push({ i,j });
        temp[i][j] = true;
        int count = 0;
        while (q.size())
        {
            count++;
            int sz = q.size();
            for (int m = 0; m < sz; m++)
            {
                int a = q.front().first;
                int b = q.front().second;
                q.pop();
                for (int k = 0; k < 4; k++)
                {
                    int x = a + dx[k];
                    int y = b + dy[k];
                    if (x >= 0 && y >= 0 && x < maze.size() && y < maze[0].size() && maze[x][y] == '.' && temp[x][y] == false)
                    {
                        if (x == 0 || y == 0 || x == maze.size() - 1 || y == maze[0].size() - 1)
                        {
                            return count;
                        }
                        q.push({ x,y });
                        temp[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
};